import React from 'react';
import { observer, inject } from "mobx-react";
import { Modal, Input, message, Button } from 'antd';
import s from './index.module.less';
import UserItem from '../../components/UserItem';

const Search = Input.Search;

@inject(({ contactsState, userState, commonState }) => ({ contactsState, userState, commonState }))
@observer
class CreateTaskModal extends React.Component {

    state = {
        loading: false,
        addIndex: null,
    }

    onSearch = (v) => {
        const { loading } = this.state;
        if (loading) return;
        const { searchContact } = this.props.contactsState;
        searchContact(v);
    }

    addContact = (id, i) => {
        const { loading } = this.state;
        if (loading) return;
        this.setState({ loading: true, addIndex: i });
        const { addContact } = this.props.contactsState;
        addContact({ userids: [id] }, () => {
            message.success('发起好友请求成功');
            this.setState({ loading: false, addIndex: null });
        });
    }

    handleCancel = () => {
        const { onCancel } = this.props;
        const { contactsState } = this.props;
        contactsState.setStateValue('friends', []);
        onCancel();
    }

    render() {
        const { show, contactsState } = this.props;
        const { friends, contactsIdObj } = contactsState;
        const { addIndex, loading } = this.state;
        return (
            <Modal
                title="添加好友"
                maskClosable={false}
                width={400}
                visible={show}
                footer={null}
                onCancel={this.handleCancel}
            >
                <div className={s.contactsSearch}>
                    <Search
                        key={!show ? Math.random() : 'search'}
                        placeholder="请输入姓名或手机号"
                        enterButton="搜索"
                        onSearch={this.onSearch}
                    />
                </div>
                <div className={s.contactslist}>
                    {friends.map((v, i) => (
                        <UserItem
                            key={v.userid}
                            username={v.phone}
                            headimage={v.headimage}
                            extra={
                                contactsIdObj[v.userid] ?
                                    <Button size={'small'} disabled>已添加</Button> :
                                    <Button size={'small'} type="primary" loading={(addIndex === i) && loading} onClick={() => this.addContact(v.userid, i)}>加好友</Button>
                            }
                        />
                    ))}
                </div>
            </Modal>
        );
    }
}

export default CreateTaskModal